package com.dem.javatestwebsocket.chathandler;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
public class MessageBroadcaster {

    private static final Set<Session> sessions = new CopyOnWriteArraySet<>();

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private ChannelTopic chatTopic;

    // 添加会话
    public void addSession(Session session) {
        sessions.add(session);
    }

    // 移除会话
    public void removeSession(Session session) {
        sessions.remove(session);
    }

    // 广播消息给所有客户端
    public void broadcast(String message) {
        redisTemplate.convertAndSend(chatTopic.getTopic(), message); // 发布消息到 Redis 频道
    }

    // 处理从 Redis 频道接收到的消息
    public void onMessage(String message) {
        for (Session session : sessions) {
            if (session.isOpen()) {
                try {
                    session.getBasicRemote().sendText(message);
                } catch (Exception e) {
                    System.err.println("广播消息时发生错误: " + e.getMessage());
                    e.printStackTrace();
                }
            }
        }
    }
}